<template>
  <div class="user-div">
    <!-- 卡片 -->
    <el-card class="user-container">
      <!-- 按钮 -->
      <el-row>
        <el-col :span="8">
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            :disabled="!multipleSelection.length"
            @click="handleDel"
            >批量删除</el-button
          >
        </el-col>
        <el-col :span="10" :offset="6">
          <span class="title">用户名称</span>
          <el-input
            v-model="name"
            size="small"
            placeholder="请输入用户名称"
          ></el-input>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="handleFind"
            >查找</el-button
          >
          <el-button
            type="success"
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
            >重置</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        border
        height="550px"
        stripe
        fit
        :data="userInfo"
        :header-cell-style="{ background: '#F5F7FA', color: '#909399' }"
        :cell-style="centerStyle"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="id" prop="id" width="47px"></el-table-column>
        <el-table-column label="头像">
          <template slot-scope="users">
            <el-avatar
              shape="square"
              :size="55"
              :src="
                users.row.avatar == null
                  ? '/avatar.jpg'
                  : baseUrl + users.row.avatar
              "
            ></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="昵称" prop="nickname"> </el-table-column>
        <el-table-column label="用户角色">
          <template slot-scope="users"
            ><el-tag>{{ users.row.role }}</el-tag></template
          >
        </el-table-column>
        <el-table-column label="登录ip" prop="ip" width="130px">
        </el-table-column>
        <el-table-column label="登录地址" prop="address" width="160px">
        </el-table-column>
        <el-table-column label="创建时间" width="185px">
          <template slot-scope="users">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ users.row.createdTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后登录时间" width="185px">
          <template slot-scope="users">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ users.row.loginTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170px">
          <template v-slot="rowInfo">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              style="padding: 7px 10px"
              @click="handleUpdate(rowInfo.row.id, rowInfo.row.role)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              style="padding: 7px 10px"
              :disabled="
                id == 1
                  ? rowInfo.row.id == id
                    ? true
                    : false
                  : rowInfo.row.role == '管理员' || rowInfo.row.role == '演示'
                  ? true
                  : false
              "
              @click="handleDel(rowInfo.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div
        class="pagination-container"
        style="float: right; margin-bottom: 15px; margin-top: 15px"
      >
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[1, 3, 5, 10]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 弹出框--编辑 -->
    <el-dialog title="修改用户" :visible.sync="dialogUpdateInfo" width="40%">
      <el-form ref="updateInfo" :rules="rules" :model="users">
        <el-form-item
          label="昵称"
          :label-width="formLabelWidth"
          prop="nickname"
        >
          <el-input
            :disabled="disabled"
            v-model="users.nickname"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="state">
          <div>
            <el-radio
              v-for="(item, index) in statusOption"
              :key="index"
              v-model="users.state"
              border
              :label="index"
              :disabled="disabled_1"
              >{{ item }}</el-radio
            >
          </div>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth" prop="role">
          <div>
            <el-radio
              v-for="(item, index) in roleOption"
              :key="index"
              v-model="users.role"
              :label="item"
              border
              :disabled="disabled_1"
              >{{ item }}</el-radio
            >
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdateInfo = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      userInfo: [],
      size: 5, //每页显示条数
      page: 1, // 当前页码
      total: 0, //总记录数
      baseUrl: "http://localhost:3000/", //后端地址
      dialogUpdateInfo: false, //控制修改用户弹框显隐
      formLabelWidth: "100px", //label宽度
      statusOption: ["正常", "禁用"],
      roleOption: ["管理员", "用户", "演示"],
      users: {}, //保存用户信息,用来回显数据
      disabled: true, //控制昵称禁用
      disabled_1: true, //控制状态禁用
      id: 1, //保存登录id
      name: "", //搜索框内容
      multipleSelection: [],
      rules: {
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { min: 4, max: 12, message: "长度在5到12个字符" },
        ],
        state: [{ required: true, message: "请选择状态", trigger: "change" }],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
    };
  },
  created() {
    this.id = sessionStorage.getItem("id");
    this.getUsers();
  },
  methods: {
    // 表格内容居中统一样式
    centerStyle() {
      return "text-align:center";
    },
    getUsers() {
      // GET /users/getUsers?page=1&size=4
      this.$http
        .get("/users/getUsers", {
          params: {
            page: this.page,
            size: this.size,
            nickname: this.name,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            // console.log(res.result);
            this.userInfo = res.result.rows;
            this.total = res.result.total;
          }
        });
    },
    // 发送请求,删除用户
    deleteUser(ids) {
      this.$http.delete(`/users/deleted`, { data: { ids } }).then((res) => {
        if (res.code == 0) {
          this.getUsers();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        }
      });
    },
    // 改变条数时,执行回调
    handleSizeChange(size) {
      this.size = size;
      // 发请求
      this.getUsers();
    },
    // 改变当前页码,执行回调
    handleCurrentChange(page) {
      this.page = page;
      this.getUsers();
    },
    // 修改用户信息
    handleUpdate(id, role) {
      // 判断登录id是不是超级管理
      if (this.id == 1) {
        this.disabled = false;
        // 判断修改的用户是否是自己
        if (id != this.id) {
          this.disabled_1 = false;
        } else {
          this.disabled_1 = true;
        }
      } else {
        this.disabled = true;
        // 判断修改的用户是不是非管理员
        if (role != "管理员" && role != "演示") {
          this.disabled_1 = false;
        } else {
          this.disabled_1 = true;
          // 判断修改的用户是不是自己
          if (id == this.id) {
            this.disabled = false;
          } else {
            this.disabled = true;
          }
        }
      }

      this.dialogUpdateInfo = true;
      // 获取数据,回显
      this.$http.get(`/users/getSingle/${id}`).then((res) => {
        if (res.code == 0) {
          this.users = res.result;
        }
      });
    },
    // 修改框确定按钮回调
    handleConfirm() {
      this.$refs.updateInfo.validate((valid) => {
        if (valid) {
          // 发送请求,修改信息
          this.$http.put("/users/update", this.users).then((res) => {
            if (res.code == 0) {
              // 提示消息
              this.$message.success(res.msg);
              // 修改弹框状态
              this.dialogUpdateInfo = false;
              // 重新获取数据
              this.getUsers();
            }
          });
        } else {
          this.$message.error("校验不通过");
          this.dialogUpdateInfo = false;
        }
      });
    },
    // 删除用户处理函数
    handleDel(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log(row.id);
          let ids = [];
          let admin_id = [];
          let flag = true;
          if (row.id) {
            ids.push(row.id);
          } else {
            this.multipleSelection.forEach((item) => {
              ids.push(item.id);
            });
            // 不能删除管理员
            this.userInfo.forEach((item) => {
              if (item.role == "管理员") {
                admin_id.push(item.id);
              }
            });
            admin_id.forEach((item) => {
              if (ids.includes(item)) {
                this.$message.error("不能删除管理员!");
                flag = false;
                return;
              }
            });
          }
          if (flag == true) {
            this.deleteUser(ids);
          }
          // console.log(ids);
          // console.log(qs.stringify(ids));
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //查找用户
    handleFind() {
      if (this.name != "") {
        this.getUsers();
        this.name = "";
      } else {
        this.$message.error("搜索名称不能为空!");
      }
    },
    // 重置表格
    resetQuery() {
      this.name = "";
      this.getUsers();
    },
    // 选择改变时回调
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>

<style lang="stylus" scoped>
.user-div
  user-select: none
  .user-container
    margin-top: 20px
    min-height: 400px
    .el-col
      .title
        font-size:14px
        font-weight:700
        color: #606266
        margin-left: 48px
      .el-input
        width: 50%
        margin-right: 10px
        margin-left: 10px
      .el-button
        padding:7px 10px
    .el-table
      margin-top: 30px
      &>>>th.el-table__cell>.cell
        text-align: center
        font-weight:bold
      &>>>.el-avatar
        img
          width: 55px
  .el-dialog
    .el-form-item
      &>>>.el-form-item__content
        width: 400px
      &>label
        font-weight:bold
</style>
